// 全局 API 客户端：自动附加 Authorization，拦截 401 尝试刷新，失败则登出并跳转登录

import { store } from '../store';
import { logout, refreshToken } from '../store/slices/authSlice';

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';

const withAuthHeaders = (init?: RequestInit): RequestInit => {
  const state = store.getState();
  const token = state.auth.user?.token;
  const headers = new Headers(init?.headers || {});
  headers.set('Content-Type', 'application/json');
  if (token) headers.set('Authorization', `Bearer ${token}`);
  return { ...init, headers };
};

const doFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
  return fetch(input, withAuthHeaders(init));
};

export const apiFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
  let res = await doFetch(input, init);
  if (res.status !== 401) return res;
  // 401：尝试无感刷新
  try {
    // 刷新 token
    await store.dispatch(refreshToken()).unwrap();
    // 使用新 token 重试原请求
    res = await doFetch(input, init);
    if (res.status !== 401) return res;
  } catch {
    // 忽略，走失败逻辑
  }
  // 刷新失败或仍未授权：登出并跳转登录
  store.dispatch(logout());
  try { window.location.href = '/login'; } catch {}
  return res;
};

export const apiRequest = async <T>(method: HttpMethod, url: string, body?: unknown): Promise<T> => {
  const res = await apiFetch(url, {
    method,
    body: body != null ? JSON.stringify(body) : undefined,
  });
  if (!res.ok) {
    const text = await res.text().catch(() => '');
    throw new Error(text || `Request failed: ${res.status}`);
  }
  return res.json() as Promise<T>;
};

export const api = {
  get: <T>(url: string) => apiRequest<T>('GET', url),
  post: <T>(url: string, body?: unknown) => apiRequest<T>('POST', url, body),
  put: <T>(url: string, body?: unknown) => apiRequest<T>('PUT', url, body),
  patch: <T>(url: string, body?: unknown) => apiRequest<T>('PATCH', url, body),
  delete: <T>(url: string) => apiRequest<T>('DELETE', url),
};




